//
//  MCNewGoodsViewController.swift
//  StoreManage
//
//  Created by MC on 2018/2/6.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

class MCNewGoodsViewController: MCViewController {

    var goodsId = 0
    var isEditGoods = false
    private var freightTemplateId = 0 // 选择的运费模板Id
    private var updateBannerImageArray = NSArray()       // 上传完的商品轮播图
    private var updateGoodsDetailImageArray = NSArray()  // 上传完的商品详情图

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        sendNetworking()
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Action
    
    @objc func titleButotnClicked() {
        let vc = MCExplainViewController()
        vc.titleStr = "新建商品说明"
        vc.code = "ba_add_goods"
        vc.type = "ba_goods"
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    @objc func keyboardConfirmClicked() {
        self.view.endEditing(true)
    }

    @objc func beginTimeViewEvent() {
        self.view.endEditing(true)
        createDatePicerView(type: 1002)
    }
    
    @objc func endTimeViewEvent() {
        self.view.endEditing(true)
        createDatePicerView(type: 1003)
    }
    
    @objc func freightViewEvent() {
        self.view.endEditing(true)
        
        let vc = MCFreightViewController()
        vc.currentFreightTemplateId = freightTemplateId
        vc.delegate = self
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    @objc func saveButtonClicked() {
        

        
        if nameView.textField.text?.count == 0 {
            MCHUD_text(message: "请填写商品名称", view: self.view, delay: 1.2)
            return
        }

        if moneyView.textField.text?.count == 0 {
            MCHUD_text(message: "请填写建议售价", view: self.view, delay: 1.2)
            return
        }
        
        if  freightView.contentButton.isSelected == false {
            MCHUD_text(message: "请选择运费模板", view: self.view, delay: 1.2)
            return
        }
        
        if  beginTimeView.contentButton.isSelected == false {
            MCHUD_text(message: "请选择上架时间", view: self.view, delay: 1.2)
            return
        }

        if  endTimeView.contentButton.isSelected == false {
            MCHUD_text(message: "请选择下架时间", view: self.view, delay: 1.2)
            return
        }

        // 商品海报图至少有一张
        if bannerImageView.dataArrayM.count == 0 {
            MCHUD_text(message: "至少选择一张商品海报图", view: self.view, delay: 1.2)
            return
        }
        
        MCHUD_default(message: "上传商品信息中...", view: self.view.window, delay: 0)
        
        // 循环上传图片
        updateBannerImages()
    }
    
    func updateBannerImages() {
        
        let bannerImageArrayM = NSMutableArray()
        var bannerImageCount = 0
        
        for _ in bannerImageView.dataArrayM {
            bannerImageArrayM.add("")
        }
        
        
        var index = 0
        
        for image in bannerImageView.dataArrayM {
            
            let i = index
            
            index += 1

            let imageData = UIImageJPEGRepresentation(image as! UIImage, 0.1)
            let base = imageData?.base64EncodedString() ?? ""
            
            let para = [
                "catalog" : "3",
                "suffix"  : "png",
                "imgBase" : base
                ] as [String : Any]
            
            MCNetwork_post(url: JAVA_imageBasePath, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
                bannerImageCount += 1
                let imgUrl = response["data"] as? String ?? ""
                
                bannerImageArrayM.replaceObject(at: i, with: imgUrl)
                
                if bannerImageCount == self.bannerImageView.dataArrayM.count {
                    self.updateBannerImageArray = bannerImageArrayM
                    self.updateGoodsDetailImages()
                }                
            }, dislike: { (response) in }) { (error) in  }
        }
    }
    
    func updateGoodsDetailImages() {
        let imageArrayM = NSMutableArray()
        
        var imageCount = 0
        
        
        
        if detailImageView.dataArrayM.count == 0 {
            self.createImageData()
            return
        }
        
        
        for _ in detailImageView.dataArrayM {
            imageArrayM.add([:])
        }
        var index = 0
        
        for image in detailImageView.dataArrayM {
           
            let i = index
            index += 1

            
            let tempImage = image as! UIImage
            
            let imageData = UIImageJPEGRepresentation(tempImage, 0.1)
            let base = imageData?.base64EncodedString() ?? ""
            
            let para = [
                "catalog" : "3",
                "suffix"  : "png",
                "imgBase" : base
                ] as [String : Any]
            
            MCNetwork_post(url: JAVA_imageBasePath, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
                imageCount += 1
                let imgUrl = response["data"] as? String ?? ""
                
                let dictM = NSMutableDictionary.init()
                dictM.setValue(imgUrl, forKey: "imagePath")
                dictM.setValue(tempImage.size.width, forKey: "imageWidth")
                dictM.setValue(tempImage.size.height, forKey: "imageHeight")

                imageArrayM.replaceObject(at: i, with: dictM)


                if imageCount == self.detailImageView.dataArrayM.count {
                    self.updateGoodsDetailImageArray = imageArrayM
                    self.createImageData()
                }
            }, dislike: { (response) in }) { (error) in  }
        }
    }
    
    
    func createImageData() {
        
        let money = Double(moneyView.textField.text!)!*100
        let moneyInt = Int(money)
        let moneyStr = String(moneyInt)
        
        var urlStr : String?
        if isEditGoods {
            urlStr = JAVA_updateStoreGoods
        } else {
            urlStr = JAVA_addStoreGoods
        }
        
        
        let para = [
            "freightTemplateId" : freightTemplateId,
            "goodsName" : nameView.textField.text ?? "",
            "suggestedPrice" : moneyStr,
            "onlineTime" : beginTimeView.contentButton.currentTitle ?? "",
            "offlineTime" : endTimeView.contentButton.currentTitle ?? "",
            "goodsNavigate" : updateBannerImageArray,
            "goodsDetail"   : updateGoodsDetailImageArray,
            "goodsId"  : goodsId
            ] as [String : Any]
        
        MCNetwork_post(url: urlStr!, para: para as [String : AnyObject], vc:
            self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            let goodsId = response["data"] as? NSNumber ?? 0
            
                
                MCHUD_hidden(view: self.view.window)
                
                
            if self.isEditGoods {
                MCHUD_text(message: "修改商品成功", view: self.view, delay: 1.2)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2, execute: {
                    self.navigationController?.popViewController(animated: true)
                })
            } else {
                MCAlterController_oneOptions(vc: self, message: "自建商品成功，前往添加规格", cancle: {
                    let vc = MCSpecificationsViewController()
                    vc.goodsId = goodsId.intValue
                    vc.type = 1
                    MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
                })
            }
            
        }, dislike: { (response) in
            MCHUD_hidden(view: self.view.window)
        }) { (error) in
            MCHUD_hidden(view: self.view.window)
        }
    }
    
    
    // MARK: - Network
    func sendNetworking() {
        
        if !isEditGoods {
            return
        }
        // 查询商品编辑详情
        let para = [
            "goodsId" : goodsId,
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_getGoodsInfo, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
        
            let dataDict = response["data"] as? [String : AnyObject] ?? [:]
            let freightTemplateId = dataDict["freightTemplateId"] as? NSNumber ?? 0
            let freightTemplateName = dataDict["freightTemplateName"] as? String ?? ""
            
            let goodsCode = dataDict["goodsCode"] as? String ?? ""
            let goodsName = dataDict["goodsName"] as? String ?? ""
            let onlineTime = dataDict["onlineTime"] as? String ?? ""
            let offlineTime = dataDict["offlineTime"] as? String ?? ""
            let suggestedPrice = dataDict["suggestedPrice"] as? NSNumber ?? 0
            let goodsNavigate = dataDict["goodsNavigate"] as? NSArray ?? []
            let goodsDetail = dataDict["goodsDetail"] as? NSArray ?? []
        
            
            self.goodsCodeView.textField.text = goodsCode
            self.nameView.textField.text = goodsName
            self.moneyView.textField.text = String.init(format: "%.2f", suggestedPrice.doubleValue/100)
            self.beginTimeView.contentButton.isSelected = true
            self.beginTimeView.contentButton.setTitle(onlineTime.MCString_prefix(index: 19), for: UIControlState.normal)
            self.endTimeView.contentButton.isSelected = true
            self.endTimeView.contentButton.setTitle(offlineTime.MCString_prefix(index: 19), for: UIControlState.normal)
            self.freightTemplateId = freightTemplateId.intValue
            self.freightView.contentButton.isSelected = true
            self.freightView.contentButton.setTitle(freightTemplateName, for: UIControlState.normal)
            
            let bannerArrayM = NSMutableArray()
            for str in goodsNavigate {
                let image = MCImage_createFromURL(fileURL: str as! String)
                bannerArrayM.add(image ?? #imageLiteral(resourceName: "Reuse_placeholder_1_1"))
            }
            self.bannerImageView.dataArrayM = bannerArrayM
       
            let goodsDetailArrayM = NSMutableArray()
            for dict in goodsDetail {
                let str = (dict as? [String:Any] ?? [:])["imagePath"]
                let image = MCImage_createFromURL(fileURL: str as! String)
                goodsDetailArrayM.add(image ?? #imageLiteral(resourceName: "Reuse_placeholder_1_1"))
            }
            self.detailImageView.dataArrayM = goodsDetailArrayM
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    // MARK: - Method
    func baseSetting() {
        self.navigationItem.titleView = titleButton
        self.view.backgroundColor = UIColor.MCGray_light
    }
    
    func createDatePicerView(type:Int) {
        let pickerView = MCDatePickerView()
        pickerView.delegate = self
        pickerView.type = type
        view.window!.addSubview(pickerView)
        pickerView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view.window!)
        }
    }
    
    func initUI() {
        view.addSubview(bgScrollView)
        bgScrollView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view).inset(UIEdgeInsetsMake(0, 0, 50, 0))
        }
        
        bgScrollView.addSubview(goodsCodeView)
        goodsCodeView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(0)
            make.width.equalTo(MCScreenWidth)
            make.height.equalTo(44)
            make.top.equalTo(bgScrollView).offset(5)
        }
        
        bgScrollView.addSubview(nameView)
        nameView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(0)
            make.width.equalTo(MCScreenWidth)
            make.height.equalTo(44)
            make.top.equalTo(goodsCodeView.snp.bottom)
        }
        
        bgScrollView.addSubview(moneyView)
        moneyView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(0)
            make.width.equalTo(MCScreenWidth)
            make.height.equalTo(44)
            make.top.equalTo(nameView.snp.bottom)
        }


        bgScrollView.addSubview(freightView)
        freightView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(0)
            make.width.equalTo(MCScreenWidth)
            make.height.equalTo(44)
            make.top.equalTo(moneyView.snp.bottom).offset(5)
        }

        bgScrollView.addSubview(beginTimeView)
        beginTimeView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(0)
            make.width.equalTo(MCScreenWidth)
            make.height.equalTo(44)
            make.top.equalTo(freightView.snp.bottom).offset(5)
        }

        bgScrollView.addSubview(endTimeView)
        endTimeView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(0)
            make.width.equalTo(MCScreenWidth)
            make.height.equalTo(44)
            make.top.equalTo(beginTimeView.snp.bottom)
        }
        
        bgScrollView.addSubview(bannerImageView)
        bannerImageView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(0)
            make.width.equalTo(MCScreenWidth)
            make.height.equalTo(130)
            make.top.equalTo(endTimeView.snp.bottom).offset(5)
        }

        bgScrollView.addSubview(detailImageView)
        detailImageView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(0)
            make.width.equalTo(MCScreenWidth)
            make.height.equalTo(130)
            make.top.equalTo(bannerImageView.snp.bottom).offset(5)
        }

        let height : CGFloat = (6*44) + 25 + 260
        
        bgScrollView.contentSize = CGSize.init(width: 0, height: height)
    
        view.addSubview(saveButton)
        saveButton.snp.remakeConstraints { (make) ->Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(50)
        }
    }
    
    func MCAddToolBar(textField:UITextField) {
        let bar = UIToolbar.init(frame: CGRect.init(x: 0, y: 0, width: MCScreenWidth, height: 44))
        let button = UIButton.init(frame: CGRect.init(x: MCScreenWidth-80, y: 7, width: 70, height: 30))
        button.layer.cornerRadius = 5
        button.layer.masksToBounds = true
        button.layer.borderColor = UIColor.MCMain.cgColor
        button.layer.borderWidth = 1
        button.setTitle("确认", for: UIControlState.normal)
        button.setTitleColor(UIColor.MCMain, for: UIControlState.normal)
        button.titleLabel?.font = MCFont(14)
        button.addTarget(self, action: #selector(keyboardConfirmClicked), for: UIControlEvents.touchUpInside)
        bar.addSubview(button)
        bar.layoutIfNeeded()
        bar.sendSubview(toBack: bar.subviews.last!)
        textField.inputAccessoryView = bar
    }
    
    // MARK: - Setter & Getter
    
    lazy var bgScrollView: UIScrollView = {
        let view = UIScrollView()
        return view
    }()
    
    lazy var goodsCodeView: MCAddTicketInputView = {
        let view = MCAddTicketInputView()
        view.titleLabel.text = "商品编码"
        view.textField.text = "暂无"
        view.textField.isEnabled = false
        return view
    }()
    

    lazy var nameView: MCAddTicketInputView = {
        let view = MCAddTicketInputView()
        view.titleLabel.text = "商品名称:"
        view.textField.placeholder = "请输入商品名称"
        view.textField.delegate = self
        view.textField.returnKeyType = UIReturnKeyType.done
        return view
    }()
    
    lazy var moneyView: MCAddTicketInputView = {
        let view = MCAddTicketInputView()
        view.titleLabel.text = "建议售价/吊牌价(元):"
        view.textField.placeholder = "请输入建议售价"
        view.textField.keyboardType = UIKeyboardType.decimalPad
        view.textField.delegate = self
        MCAddToolBar(textField: view.textField)
        return view
    }()

    lazy var freightView: MCAddTicketEventView = {
        let view = MCAddTicketEventView()
        view.titleLabel.text = "设置运费模板:"
        view.contentButton.setTitle("请选择运费模板", for: UIControlState.normal)
        view.contentButton.addTarget(self, action: #selector(freightViewEvent), for: UIControlEvents.touchUpInside)
    
        return view
    }()
    
    lazy var beginTimeView: MCAddTicketEventView = {
        let view = MCAddTicketEventView()
        view.titleLabel.text = "上架时间:"
        view.contentButton.setTitle("请选择上架时间", for: UIControlState.normal)
        view.contentButton.addTarget(self, action: #selector(beginTimeViewEvent), for: UIControlEvents.touchUpInside)
        return view
    }()

    lazy var endTimeView: MCAddTicketEventView = {
        let view = MCAddTicketEventView()
        view.titleLabel.text = "下架时间:"
        view.contentButton.setTitle("请选择下架时间", for: UIControlState.normal)
        view.contentButton.addTarget(self, action: #selector(endTimeViewEvent), for: UIControlEvents.touchUpInside)

        return view
    }()

    lazy var bannerImageView: MCNewGoodsAddImagesView = {
        let view = MCNewGoodsAddImagesView()
        view.promptLabel.text = "商品海报图 (最多上传6张)"
        view.isNeedEditImage = true
        view.bigImageCount = 6
        view.superViewController = self
        return view
    }()
    
    lazy var detailImageView: MCNewGoodsAddImagesView = {
        let view = MCNewGoodsAddImagesView()
        view.promptLabel.text = "商品详图 (最多上传10张)"
        view.isNeedEditImage = false
        view.bigImageCount = 10
        view.superViewController = self
        return view
    }()
    
    lazy var saveButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.backgroundColor = UIColor.MCMain
        button.titleLabel?.font = MCFont(14)
        button.setTitle("保存", for: UIControlState.normal)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.addTarget(self, action: #selector(saveButtonClicked), for: UIControlEvents.touchUpInside)
        return button
    }()
    
    lazy var titleButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.titleLabel?.font = MCFont(19)
        button.frame = CGRect.init(x: 0, y: 0, width: 90, height: 30)
        button.setTitleColor(UIColor.black, for: UIControlState.normal)
        button.setTitle("商品编辑", for: UIControlState.normal)
        button.setImage(#imageLiteral(resourceName: "Reuse_question"), for: UIControlState.normal)
        button.imageEdgeInsets = UIEdgeInsetsMake(0, 78, 0, -78)
        button.titleEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 15)
        button.addTarget(self, action: #selector(titleButotnClicked), for: UIControlEvents.touchUpInside)
        return button
    }()
}

extension MCNewGoodsViewController : MCDatePickerViewDelegate {
    func MCDatePickerViewSelectedRow(type: Int, str: String) {
        self.view.endEditing(true)
        switch type {
        case 1002:
            beginTimeView.contentButton.isSelected = true
            beginTimeView.contentButton.setTitle(str, for: UIControlState.normal)
        case 1003:
            endTimeView.contentButton.isSelected = true
            endTimeView.contentButton.setTitle(str, for: UIControlState.normal)
        default:
            break
        }
    }
}

extension MCNewGoodsViewController : MCFreightViewControllerDelegate {    
    
    func MCFreightViewControllerSelectedFreightTemplate(model: MCFreightModel) {
        self.view.endEditing(true)
        freightTemplateId = model.freightTemplateId.intValue
        freightView.contentButton.isSelected = true
        freightView.contentButton.setTitle(model.name, for: UIControlState.normal)
    }
}


extension MCNewGoodsViewController : UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return true
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if moneyView.textField == textField {
            let b = MCString_keepTwoDecimalPlaces(textField, range, string)
            return b
        }
        return true
    }
}
